<template>
    <div >
      <el-form ref="ruleFormRef"   v-loading="loading" :model="ruleForm" status-icon :rules="rules" label-width="auto"
        class="demo-ruleForm">

        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" type="text" clearable placeholder="请输入角色名称" autocomplete="off" :disabled="disabled" />
        </el-form-item>
        <!-- <el-form-item label="权限" prop="roles">
          <div style="background: #f1f1f1;width: 100%;border-radius: 10px;">
            <el-tree
            ref="treeRef"
          style="max-height: 60vh;overflow-y: auto;background: none;margin: 10px;"
            v-model="ruleForm.roles"
            :data="routerTree"
            placeholder="请选择权限"
            default-expand-all
            
            show-checkbox
            node-key="name"
            :expand-on-click-node="false"
            :props="{ class: customNodeClass }"
            />
          </div>
        <el-button size="large"  type="primary" @click="getCheckedNodes">获取</el-button>

        </el-form-item> -->
       
       
        <el-form-item label="状态" prop="status">
          <el-switch v-model="ruleForm.status" :active-value="1"  active-text="启用"  :inactive-value="2" inactive-text="禁用">
            </el-switch>
  
        </el-form-item>
        <el-form-item label="备注" prop="content">
          <el-input v-model="ruleForm.content" autosize :disabled="disabled"
          type="textarea" placeholder="请输入内容" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="props.type !== 'info'">
          <el-button size="large"  type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
          <el-button size="large" @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  <script lang="ts" setup>
  import type Node from 'element-plus/es/components/tree/src/model/node'
import type { TreeNodeData } from 'element-plus/es/components/tree/src/tree.type'
  import { onMounted, reactive, ref,defineEmits,defineProps,  getCurrentInstance } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useRoute,useRouter } from "vue-router";
  import router from '../../../router';
  import {roleApi} from '@/utils/api/role'; 
  import { ElMessage } from 'element-plus'
import { fa } from 'element-plus/es/locales.mjs';
  const { proxy } = getCurrentInstance(); // 获取当前Vue实例的代理对象，用于访问全局属性。
  
  interface Tree {
  id: number
  label: string
  isPenultimate?: boolean
  children?: Tree[]
}

  const props = defineProps({
    id: Number,
    type: String
  });
  const disabled = ref(false)
  if(props.type ==='info'){
    disabled.value = true
  }
  
const customNodeClass = ({ isPenultimate }: TreeNodeData, node: Node) =>{
  return isPenultimate ? 'is-penultimate' : ''
}
  // 定义自定义事件
  const emits = defineEmits(['close-dialog']);
  // 使用 useRoute 获取参数
 
// 获取所有路由信息

const generateRouteTree = (routes)=> {
  return routes.map(route => {
    const newRoute = { 
      path: route.path,
      label:route.title,
      name:route.name,
      meta:route.meta || null,
     
     };
    if (route.children && route.children.length > 0) {
      newRoute.children = generateRouteTree(route.children);
    }
    if(newRoute.meta && newRoute.meta.button && newRoute.meta.api && newRoute.meta.isPenultimate){
      const roles = newRoute.meta.button
      newRoute.isPenultimate = true
      const buttonArr = roles.map((role) => ({ label:role.title, type:role.type,value: role.value}));
      const apis = newRoute.meta.api

      const ApiArr = apis.map((role) => ({ label:role.title, type:role.type,value: role.value}));

      newRoute.children = buttonArr.concat(ApiArr)
    }
    return newRoute;
  });
}

// 构建路由树
const routerTree : Tree[] = generateRouteTree(router.options.routes)//generateRouteTree(router.options.routes);
const treeRef = ref<InstanceType<typeof ElTree>>()

const getCheckedNodes = () => {
}
  const loading = ref(false)
  
  // 获取个人信息
  const getInfo =  async(id:string) => {
    // 这里是获取个人信息的接口
    loading.value = true
     const res =  await roleApi.info({id:id})
    loading.value = false
    Object.assign(ruleForm,res.data)
  }
  
  const ruleFormRef = ref < FormInstance > ()
  
  interface IForm {
    id : string
    name: string,
    content:string,
    status:Number,
  }
  
  const ruleForm = reactive<IForm>({
    id:null,
    name: null,
    content:null,
    status:1,
  })
  
  const rules = reactive<FormRules<typeof ruleForm>>({
    name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  })
  
  const submitForm = (formEl: FormInstance | undefined) => {
    
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        loading.value = true
        if(ruleForm.id == null){
          roleApi.create(ruleForm).then((res) => {
          loading.value = false
            if (res.code === 200) {
              emits('close-dialog');
            }else{
              ElMessage.error(res.msg)
            }
          })
        }else{
          roleApi.update(ruleForm).then((res) => {
            loading.value = false
            if (res.code === 200) {
              emits('close-dialog');
            }else{
              ElMessage.error(res.msg)
            }
          })
        }
       
      } else {
        loading.value = false
  
      }
    })
  }
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  onMounted(  () => {
    // 获取数据
    if(props.id){
      getInfo(props.id)
    }
  
   
  })
  </script>
  
  <style scoped>
  .demo-ruleForm {
   background: #fff;
   margin-top: 10px;
  }

  
  </style>
  <style>
.is-penultimate > .el-tree-node__content {
  color: #626aef;
}

.el-tree .el-tree-node.is-penultimate > .el-tree-node__children {
  display: flex;
  flex-direction: row;
}
.is-penultimate > .el-tree-node__children > div {
  width: auto;
}
</style>
  